package com.ddtech.config;

import com.ddtech.exception.handler.ApiError;
import com.ddtech.framework.security.constant.SysConstant;
import com.ddtech.utils.ApiResult;
import com.ddtech.utils.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.LinkedHashMap;

/**
 * 处理app返回结果
 *
 * @author bin
 * @date 2023-06-10
 */
@RestControllerAdvice
public class AppResponseDataAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object data,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        HttpHeaders headers = serverHttpRequest.getHeaders();
        String clientId = headers.getFirst("clientId");
        if (StringUtils.isNotBlank(clientId) && SysConstant.VR.equals(clientId)) {
            if (data == null) {
                //就去返回上方的默认返回对象
                return ApiResult.success();
                //如果响应本身就是ReturnMessage，即你指定的返回对象
            } else if (data instanceof ResponseEntity) {
                //进行强转
                return ApiResult.success(((ResponseEntity<?>) data).getBody());
            } else if (data instanceof ApiError) {
                //错误
                return ApiResult.fail(((ApiError) data).getMessage());
            } else if (data instanceof LinkedHashMap && Integer.valueOf(HttpStatus.UNAUTHORIZED.value()).equals(((LinkedHashMap<?, ?>) data).get("status"))) {
                return ApiResult.fail(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期,请重新登录！");
            } else {
                //如果都不满足就将Controller返回的数据set到响应数据中
                return ApiResult.success(data);
            }
        }
        return data;
    }
}
